<template>
  <div class="menus-container">
    <div class="page-header">
      <h2>菜单管理</h2>
      <el-button type="primary" @click="handleAddMenu" size="default">
        <el-icon><component is="i-plus" /></el-icon>
        添加菜单
      </el-button>
    </div>
    
    <!-- 搜索和筛选 -->
    <el-card class="search-card" shadow="hover">
      <el-form :model="searchForm" class="search-form">
        <el-form-item label="菜单名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入菜单名称"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item label="父菜单">
          <el-select
            v-model="searchForm.parent_id"
            placeholder="请选择父菜单"
            clearable
            size="small"
          >
            <el-option
              v-for="menu in menusList"
              :key="menu.id"
              :label="menu.name"
              :value="menu.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" size="small">
            <el-icon><component is="i-search" /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch" size="small">
            <el-icon><component is="i-refresh-left" /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 菜单表格 -->
    <el-card class="menus-table-card" shadow="hover">
      <el-table
        :data="menusData"
        style="width: 100%"
        border
        v-loading="loading"
        element-loading-text="加载中..."
      >
        <el-table-column prop="id" label="ID" width="80" fixed />
        <el-table-column prop="name" label="菜单名称" width="180" />
        <el-table-column prop="path" label="路径" width="180" />
        <el-table-column prop="component" label="组件路径" width="250" />
        <el-table-column prop="icon" label="图标" width="120">
          <template #default="{ row }">
            <el-tag size="small" type="info">{{ row.icon || '-' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="parent_id" label="父菜单ID" width="120" />
        <el-table-column prop="sort_order" label="排序" width="80" />
        <el-table-column prop="is_visible" label="是否可见" width="100">
          <template #default="{ row }">
            <el-switch
              v-model="row.is_visible"
              disabled
              active-color="#10b981"
              inactive-color="#d1d5db"
            />
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="handleEditMenu(row)"
              :disabled="editingId === row.id"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDeleteMenu(row)"
              :disabled="deletingId === row.id"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 添加/编辑菜单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加菜单' : '编辑菜单'"
      width="700px"
      destroy-on-close
    >
      <el-form
        :model="menuForm"
        :rules="menuRules"
        ref="menuFormRef"
        label-width="100px"
        class="menu-form"
      >
        <el-form-item label="菜单名称" prop="name">
          <el-input
            v-model="menuForm.name"
            placeholder="请输入菜单名称"
          />
        </el-form-item>
        
        <el-form-item label="菜单路径" prop="path">
          <el-input
            v-model="menuForm.path"
            placeholder="请输入菜单路径"
          />
        </el-form-item>
        
        <el-form-item label="组件路径" prop="component">
          <el-input
            v-model="menuForm.component"
            placeholder="请输入组件路径"
          />
        </el-form-item>
        
        <el-form-item label="菜单图标" prop="icon">
          <el-input
            v-model="menuForm.icon"
            placeholder="请输入菜单图标"
          />
          <div class="form-tip">例如：i-s-grid, i-user, i-setting</div>
        </el-form-item>
        
        <el-form-item label="父菜单" prop="parent_id">
          <el-select
            v-model="menuForm.parent_id"
            placeholder="请选择父菜单"
            clearable
          >
            <el-option
              v-for="menu in menusList"
              :key="menu.id"
              :label="menu.name"
              :value="menu.id"
              :disabled="dialogType === 'edit' && menu.id === menuForm.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="排序" prop="sort_order">
          <el-input-number v-model="menuForm.sort_order" :min="0" :max="999" />
        </el-form-item>
        
        <el-form-item label="是否可见" prop="is_visible">
          <el-switch
            v-model="menuForm.is_visible"
            active-color="#10b981"
            inactive-color="#d1d5db"
          />
        </el-form-item>
        
        <el-form-item label="权限选择">
          <el-checkbox-group v-model="menuForm.permission_ids" class="permission-checkbox-group">
            <el-checkbox
              v-for="permission in permissions"
              :key="permission.id"
              :label="permission.id"
              class="permission-checkbox"
            >
              {{ permission.name }} - {{ permission.description }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="handleSubmit"
            :loading="dialogLoading"
          >
            {{ dialogLoading ? '提交中...' : '确定' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

export default {
  name: 'Menus',
  setup() {
    const loading = ref(false)
    const dialogVisible = ref(false)
    const dialogType = ref('add') // 'add' or 'edit'
    const dialogLoading = ref(false)
    const menuFormRef = ref(null)
    const editingId = ref(null)
    const deletingId = ref(null)
    
    // 搜索表单
    const searchForm = reactive({
      name: '',
      parent_id: ''
    })
    
    // 分页
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0
    })
    
    // 菜单表单
    const menuForm = reactive({
      id: '',
      name: '',
      path: '',
      component: '',
      icon: '',
      parent_id: null,
      sort_order: 0,
      is_visible: true,
      permission_ids: []
    })
    
    // 表单验证规则
    const menuRules = {
      name: [
        { required: true, message: '请输入菜单名称', trigger: 'blur' },
        { max: 100, message: '菜单名称不能超过100个字符', trigger: 'blur' }
      ],
      path: [
        { max: 255, message: '菜单路径不能超过255个字符', trigger: 'blur' }
      ],
      component: [
        { max: 255, message: '组件路径不能超过255个字符', trigger: 'blur' }
      ],
      icon: [
        { max: 100, message: '图标不能超过100个字符', trigger: 'blur' }
      ],
      sort_order: [
        { type: 'number', message: '排序号必须是数字', trigger: 'blur' },
        { min: 0, message: '排序号不能小于0', trigger: 'blur' }
      ]
    }
    
    // 菜单数据
    const menusData = ref([])
    const menusList = ref([])
    const permissions = ref([])
    
    // 获取权限列表
    const fetchPermissions = async () => {
      try {
        const response = await axios.get('/api/permissions?page_size=100')
        if (response.data.code === 200) {
          permissions.value = response.data.data.items || []
        } else {
          ElMessage.error('获取权限列表失败')
        }
      } catch (error) {
        ElMessage.error('获取权限列表失败')
        console.error('获取权限列表失败:', error)
      }
    }
    
    // 获取所有菜单（用于下拉选择）
    const fetchAllMenus = async () => {
      try {
        const response = await axios.get('/api/menus', {
          params: {
            page_size: 100,
            page: 1
          }
        })
        if (response.data.code === 200) {
          menusList.value = response.data.data.items || []
        } else {
          ElMessage.error('获取菜单列表失败')
        }
      } catch (error) {
        ElMessage.error('获取菜单列表失败')
        console.error('获取菜单列表失败:', error)
      }
    }
    
    // 获取菜单数据
    const fetchMenus = async () => {
      loading.value = true
      try {
        // 构建参数，处理parent_id类型问题
        const params = {
          page: pagination.currentPage,
          page_size: pagination.pageSize,
          name: searchForm.name
        }
        
        // 只有当parent_id不为空字符串时才添加到参数中
        if (searchForm.parent_id !== '') {
          params.parent_id = parseInt(searchForm.parent_id) || null
        }
        
        const response = await axios.get('/api/menus', { params })
        if (response.data.code === 200) {
          menusData.value = response.data.data.items || []
          pagination.total = response.data.data.total || 0
        } else {
          ElMessage.error('获取菜单数据失败')
        }
      } catch (error) {
        ElMessage.error('获取菜单数据失败')
        console.error('获取菜单数据失败:', error)
      } finally {
        loading.value = false
      }
    }
    
    // 处理搜索
    const handleSearch = () => {
      pagination.currentPage = 1
      fetchMenus()
    }
    
    // 重置搜索
    const resetSearch = () => {
      searchForm.name = ''
      searchForm.parent_id = ''
      pagination.currentPage = 1
      fetchMenus()
    }
    
    // 处理分页大小变化
    const handleSizeChange = (size) => {
      pagination.pageSize = size
      fetchMenus()
    }
    
    // 处理页码变化
    const handleCurrentChange = (current) => {
      pagination.currentPage = current
      fetchMenus()
    }
    
    // 打开添加菜单对话框
    const handleAddMenu = () => {
      dialogType.value = 'add'
      menuForm.id = ''
      menuForm.name = ''
      menuForm.path = ''
      menuForm.component = ''
      menuForm.icon = ''
      menuForm.parent_id = null
      menuForm.sort_order = 0
      menuForm.is_visible = true
      menuForm.permission_ids = []
      dialogVisible.value = true
      
      // 重置表单验证
      setTimeout(() => {
        if (menuFormRef.value) {
          menuFormRef.value.resetFields()
        }
      }, 100)
    }
    
    // 打开编辑菜单对话框
    const handleEditMenu = async (row) => {
      dialogType.value = 'edit'
      editingId.value = row.id
      
      try {
        // 获取菜单详情
        const response = await axios.get(`/api/menus/${row.id}`)
        if (response.data.code === 200) {
          const menu = response.data.data
          menuForm.id = menu.id
          menuForm.name = menu.name
          menuForm.path = menu.path
          menuForm.component = menu.component
          menuForm.icon = menu.icon
          menuForm.parent_id = menu.parent_id
          menuForm.sort_order = menu.sort_order
          menuForm.is_visible = menu.is_visible
          menuForm.permission_ids = menu.permissions.map(p => p.id) || []
          dialogVisible.value = true
        } else {
          ElMessage.error('获取菜单详情失败')
        }
      } catch (error) {
        ElMessage.error('获取菜单详情失败')
        console.error('获取菜单详情失败:', error)
      } finally {
        editingId.value = null
      }
    }
    
    // 提交表单
    const handleSubmit = async () => {
      if (!menuFormRef.value) return
      
      try {
        await menuFormRef.value.validate()
        dialogLoading.value = true
        
        if (dialogType.value === 'add') {
          // 创建菜单
          const response = await axios.post('/api/menus', menuForm)
          if (response.data.code === 200) {
            ElMessage.success('菜单创建成功')
            dialogVisible.value = false
            fetchMenus()
            fetchAllMenus()
          } else {
            ElMessage.error(response.data.message || '菜单创建失败')
          }
        } else {
          // 更新菜单
          const response = await axios.put(`/api/menus/${menuForm.id}`, menuForm)
          if (response.data.code === 200) {
            ElMessage.success('菜单更新成功')
            dialogVisible.value = false
            fetchMenus()
            fetchAllMenus()
          } else {
            ElMessage.error(response.data.message || '菜单更新失败')
          }
        }
      } catch (error) {
        if (error.name === 'ValidationError') {
          return
        }
        ElMessage.error('操作失败')
        console.error('操作失败:', error)
      } finally {
        dialogLoading.value = false
      }
    }
    
    // 删除菜单
    const handleDeleteMenu = async (row) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除菜单 "${row.name}" 吗？`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        deletingId.value = row.id
        const response = await axios.delete(`/api/menus/${row.id}`)
        
        if (response.data.code === 200) {
          ElMessage.success('菜单删除成功')
          fetchMenus()
          fetchAllMenus()
        } else {
          ElMessage.error(response.data.message || '菜单删除失败')
        }
      } catch (error) {
        if (error.name !== 'Error') {
          ElMessage.info('已取消删除')
        } else {
          ElMessage.error('删除失败')
          console.error('删除失败:', error)
        }
      } finally {
        deletingId.value = null
      }
    }
    
    // 初始化
    onMounted(() => {
      fetchPermissions()
      fetchAllMenus()
      fetchMenus()
    })
    
    return {
      loading,
      dialogVisible,
      dialogType,
      dialogLoading,
      menuFormRef,
      editingId,
      deletingId,
      searchForm,
      pagination,
      menuForm,
      menuRules,
      menusData,
      menusList,
      permissions,
      handleSearch,
      resetSearch,
      handleSizeChange,
      handleCurrentChange,
      handleAddMenu,
      handleEditMenu,
      handleSubmit,
      handleDeleteMenu
    }
  }
}
</script>

<style scoped>
.menus-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  align-items: flex-end;
  gap: 16px;
}

.menus-table-card {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.menu-form {
  max-height: 500px;
  overflow-y: auto;
}

.form-tip {
  margin-top: 8px;
  font-size: 12px;
  color: #666;
}

.permission-checkbox-group {
  max-height: 200px;
  overflow-y: auto;
  padding: 10px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
}

.permission-checkbox {
  display: block;
  margin-bottom: 8px;
}
</style>